package com.LeeCode;

import java.util.ArrayList;
import java.util.List;

/**
 * 组合总和
 */
public class Code039 {
    public static void main(String[] args) {
        int[] nums = {2, 3, 5};
        int target = 8;
        System.out.println(new Code039().combinationSum(nums, target));
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        backtrace(candidates, res, target, new ArrayList<>(), 0);
        return res;
    }

    public void backtrace(int[] candidates, List<List<Integer>> res, int target, List<Integer> cur, int index) {
        if (target == 0) {
            res.add(new ArrayList<>(cur));
            return;
        }

        if (index == candidates.length) {
            return;
        }

        backtrace(candidates, res, target, cur, index + 1);
        if (target - candidates[index] >= 0) {
            cur.add(candidates[index]);
            backtrace(candidates, res, target - candidates[index], cur, index);
            cur.remove(cur.size() - 1);
        }
    }
}
